package com.lxg.shibie;

import okhttp3.*;
import org.json.JSONObject;

import java.io.*;

import java.net.URLEncoder;
import java.nio.file.Files;
import java.nio.file.Paths;
import java.util.Base64;


/**
 * 语音转文字测试类（百度云）
 */
public class Speech {
    public static final String API_KEY = "k148GcjMPDVwLdl5ABIULcxB";
    public static final String SECRET_KEY = "ER9rsQfoYN2hb2vCnzxrQCqE6vf2FoSv";

    static final OkHttpClient HTTP_CLIENT = new OkHttpClient().newBuilder().build();

    public static void main(String []args) throws IOException{
        MediaType mediaType = MediaType.parse("application/json");
        String filePath = "src/main/resources/static/test.wav";
        // speech 可以通过 getFileContentAsBase64("C:\fakepath\7d7adb27-98ab-40f1-a8a6-65732924d7c5.mp3") 方法获取,如果Content-Type是application/x-www-form-urlencoded时,使用getFileContentAsBase64Urlencoded方法获取

        byte[] b = Files.readAllBytes(Paths.get(filePath));
        String base64 = Base64.getEncoder().encodeToString(b);
        System.out.println(b.length);
        System.out.println(base64);
        String token = Token.getToken(API_KEY,SECRET_KEY);
        System.out.println(token);


        RequestBody body = RequestBody.create(mediaType, "{\"format\":\"m4a\",\"rate\":16000,\"channel\":1,\"cuid\":\"1\",\"dev_pid\":80001,\"speech\":\""+base64+"\",\"len\":"+b.length+",\"token\":\"" + token + "\"}");
        Request request = new Request.Builder()
                .url("https://vop.baidu.com/pro_api")
                .method("POST", body)
                .addHeader("Content-Type", "application/json")
                .addHeader("Accept", "application/json")
                .build();
        Response response = HTTP_CLIENT.newCall(request).execute();
        System.out.println(response.body().string());

    }

    /**
     * 获取文件base64编码
     * @param path 文件路径
     * @return base64编码信息，不带文件头
     * @throws IOException IO异常
     */
    static String getFileContentAsBase64(String path) throws IOException {
        byte[] b = Files.readAllBytes(Paths.get(path));
        return Base64.getEncoder().encodeToString(b);
    }
    /**
     * 获取文件base64 UrlEncode编码
     * @param path 文件路径
     * @return base64编码信息，不带文件头
     * @throws IOException IO异常
     */
    static String getFileContentAsBase64Urlencoded(String path) throws IOException {
        return URLEncoder.encode(getFileContentAsBase64(path), "utf-8");
    }


    /**
     * 从用户的AK，SK生成鉴权签名（Access Token）
     *
     * @return 鉴权签名（Access Token）
     * @throws IOException IO异常
     */


}